package Test1;

import java.util.ArrayList;
import java.util.Arrays;

public class TestClass {
    private static void testMethod(){
        System.out.println("testMethod");
    }
    public static void main(String[] args) {
        int[] array = new int[]{-2,0,0,2,2};
        threeSum(array);

    }
    public static ArrayList<ArrayList<Integer>> threeSum (int[] num) {
        // write code here
        Arrays.sort(num);
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        for (int i = 0; i < num.length-2; i++) {
            if(num[i] > 0 ) break;
            if(i>0 && num[i] == num[i+1]) continue;
            int left = i+1,right = num.length-1;
            while (left < right) {
                int sum = num[i]+num[left]+num[right];
                if(sum == 0) {
                    ArrayList<Integer> arrayList = new ArrayList<>();
                    arrayList.add(num[i]);
                    arrayList.add(num[left]);
                    arrayList.add(num[right]);
                    list.add(arrayList);
                    while (left < right && num[left] == num[left+1]) {
                        left++;
                    }
                    while (left < right && num[right] == num[right-1]) {
                        right--;
                    }
                    left++;
                    right--;
                } else if(sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return list;
    }
}
